/**
 * Created by dale on 2017/8/22.
 */
var keyId;
var  planList;
var iDepId;
var searchbtn;
var AddTarget;
$(document).ready(function () {
    planList= $('#planList');
    $('.xh-datagrid-toolbar').parseToolbar();
    //设置禁用
    $('#bt_list_del').setButtonDisable('eu');
    $('#bt_list_confirm').setButtonDisable('eu');
    $('#bt_list_unConfirm').setButtonDisable('eu');
    $('#bt_list_transList').setButtonDisable('eu');
    $('#bt_list_getStuTablet').setButtonDisable('eu');
    $('#bt_list_seeApplyTablet').setButtonDisable('eu');

    var startDom    = $('#List_Search_StartTime'),
        endDom      = $('#List_Search_EndTime');
    searchbtn=$('#bt_list_search');
    startDom.datebox();
    endDom.datebox();
    xhTool.bindDocKeyDown($('#bt_list_search'));

    //menuButton初始化绑定事件
    if($('#mb').length > 0){
        var  $btn_menu=$('#mb').menubutton({
            iconCls: 'fa fa-bars',
            menu: '#mm2'
        });
        $($btn_menu.menubutton('options').menu).menu({
            onClick: function (item) {
                //item 的相关属性参见API中的menu
                var key=xhExtra.getValue($('#list_search'));
                var startTime=xhExtra.getValue($('#List_Search_StartTime'));
                var endTime=xhExtra.getValue($('#List_Search_EndTime'));
                var province=$('#select_province').combobox('getText');
                var city=$('#select_city').combobox('getText');
                if (item.text == '导出流程计划') {
                    var type=xhExtra.getValue($('#select_status'));
                    var tsort=xhExtra.getValue($('#select_sort'));
                    var sNodeName = xhExtra.getValue($('#select_node'));
                    window.open(modelUrl+'plan/exportPlan?key='+key+'&startTime='+startTime+'&endTime='+endTime+'&sNodeName='+sNodeName+'&type='+type+'&tsort='+tsort+'&province='+province+'&city='+city);
                } else if(item.text == '导出流转单'){
                    window.open(modelUrl+'plan/exportPlanTrans?key='+key+'&startTime='+startTime+'&endTime='+endTime+'&province='+province+'&city='+city);
                }
            }
        });

    }

    if($('#bt_node_applyTab').length > 0){
        var  $applyTab_menu=$('#bt_node_applyTab').menubutton({
            iconCls: 'fa fa-cog',
            menu: '#mm3'
        });
        $($applyTab_menu.menubutton('options').menu).menu({
            onClick: function (item) {
                //item 的相关属性参见API中的menu
                if(planList.treegrid('getSelections').length==0){
                    window.top.swal('错误','请选择一个计划','error');
                    return false;
                }
                var id=planList.treegrid('getSelections')[0]['realId'];
                var type=planList.treegrid('getSelections')[0]['type'];
                if (type != 1) {
                    window.top.swal('错误','请选择一个计划主节点','error');
                    return false;
                }
                if (item.text == '关闭平板领用') {
                    xhExtra.askChangeStatus('bpm/plan/closePlanApplyTab/close',{iBBPId:id},null,'确定要关闭平板领用么?',function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        planList.treegrid('reload');
                    });
                } else if(item.text == '开启平板领用'){
                    xhExtra.askChangeStatus('bpm/plan/closePlanApplyTab/open',{iBBPId:id},null,'确定要开启平板领用么?',function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        planList.treegrid('reload');
                    });
                }
            }
        });
    }


    var openId=addressUri.getParam('openId');
    var finish=addressUri.getParam('finish');
    if(openId!=null){
        var queryParams={'openId':openId};
    }else{
        queryParams=null;
    }
    planList.treegrid({
        queryParams:queryParams,
        onSelect:function (row) {
            row['_parentId'] = 'P-'+row['iBPPId'];
            keyId=row['keyId'];
            planList.treegrid('expand',keyId);
            if(row['type']==1){
                $('#bt_list_del').setButtonEnable('eu');
                $('#bt_list_confirm').setButtonEnable('eu');
                $('#bt_list_unConfirm').setButtonEnable('eu');
                $('#bt_list_transList').setButtonEnable('eu');
                $('#bt_list_getStuTablet').setButtonEnable('eu');
                $('#bt_list_seeApplyTablet').setButtonEnable('eu');
            }else {
                $('#bt_list_del').setButtonDisable('eu');
                $('#bt_list_confirm').setButtonDisable('eu');
                $('#bt_list_unConfirm').setButtonDisable('eu');
                $('#bt_list_transList').setButtonDisable('eu');
                $('#bt_list_getStuTablet').setButtonDisable('eu');

                $('#bt_list_seeApplyTablet').setButtonDisable('eu');
            }
        },
        onBeforeSelect:function (row) {
            if(keyId==undefined){
                return true;
            }else {
                if(keyId==row['keyId']){
                    planList.treegrid('unselect',keyId);
                    planList.treegrid('collapse',keyId);
                    keyId=null;
                    $('#bt_list_del').setButtonDisable('eu');
                    $('#bt_list_confirm').setButtonDisable('eu');
                    $('#bt_list_unConfirm').setButtonDisable('eu');
                    $('#bt_list_transList').setButtonDisable('eu');
                    $('#bt_list_getStuTablet').setButtonDisable('eu');
                    $('#bt_list_seeApplyTablet').setButtonDisable('eu');
                    return false;
                }
            }
        },
        onBeforeCheck:function (row) {
            if(keyId==undefined){
                return true;
            }else {
                if(keyId==row['keyId']){
                    planList.treegrid('uncheckRow',keyId);
                    keyId=null;
                    $('#bt_list_del').setButtonDisable('eu');
                    $('#bt_list_confirm').setButtonDisable('eu');
                    $('#bt_list_unConfirm').setButtonDisable('eu');
                    $('#bt_list_transList').setButtonDisable('eu');
                    $('#bt_list_getStuTablet').setButtonDisable('eu');
                    $('#bt_list_alterCharger').setButtonDisable('eu');
                    $('#bt_list_seeApplyTablet').setButtonDisable('eu');
                    return false;
                }
            }
        },
        onDblClickRow:function (row) {
            if(finish==1){
                return false;
            }
            if(row['type']==2){
                window.top.xhTop.showModal({
                    title:'编辑'+row['name'],
                    content: '<iframe src="'+modelUrl+'plan/contentForm?id='+row['iBPCId']+'"  style="width: 100%;;border-style: none;padding: 0px;height: 360px"  scrolling="yes"   ></iframe>',
                    button:'提交',
                    size:'lg',
                    backClose:false,
                });
            }else {
                return false;
            }

        },
        onLoadSuccess:function (row,data) {
            // if(AddTarget==null){
            //    AddTarget=$('<div id="total" style="display: inline;margin-left: 10px">'+data['numTotal']+'</div>').appendTo('#depList_toolbar');
            // }else {
            //     AddTarget.remove();
            //     AddTarget=$('<div id="total" style="display: inline;margin-left: 10px">'+data['numTotal']+'</div>').appendTo('#depList_toolbar');
            // }

        }
    });

    //获取平板
    $('#bt_list_getTablet').click(function (){
        var row = planList.treegrid('getSelected');
        var parent = planList.treegrid('getParent' , row.keyId);
        if(parent['iSchoolId'] == ''||parent['iSchoolId'] == null){
            window.top.xhTop.showError('错误' , '该记录未关联学校');
            return  false;
        }
        if (parent['bApplyTab'] == 0) {
            window.top.xhTop.showError('错误' , '该节点已关闭平板领用');
            return false;
        }
        // var userInfo = JSON.parse(xhTool.getCookie('userInfo'));
        if (row['sNodeName'] =='产品筹备过程'  && userId == row['iChargeId'] ){
            window.top.xhTop.showModal({
                title:'申请领用-'+parent['name'],
                content: '<iframe src="'+modelUrl+'plan/planTablet?iBPPId='+parent['realId']+'&schoolId='+parent['iSchoolId']+'"  style="width: 100%;;border-style: none;padding: 0px;height: 250px"  scrolling="yes"   ></iframe>',
                button:'提交',
                backClose:false
            });
        } else {
             window.top.xhTop.showError('错误','没有权限或不在该节点申请');
            return  false;
        }

    });


    $('#bt_list_transList').click(function () {  //流转单
        if(xhExtra.buttonDisabled($(this))){
            return false;
        }
        var id=planList.treegrid('getSelections')[0]['realId'];
        var type=planList.treegrid('getSelections')[0]['type'];
        var name=planList.treegrid('getSelections')[0]['sSchoolName'];

        if(type==1){
            window.top.xhTop.showModal({
                title:'流转单',
                content: '<iframe src="'+modelUrl+'plan/transForm?iBPPId='+id+'&name='+escape(name)+'"  style="width: 100%;;border-style: none;padding: 0px;height: 450px"  scrolling="yes"   ></iframe>',
                size:'lg',
                button:'提交',
                backClose:false,
                extraBtn: {doPrint: '打印'}
            });
        }
    });

    if(finish!=1) {
        // $('#bt_list_export').click(function () {
        //     var key=xhExtra.getValue($('#list_search'));
        //     var startTime=xhExtra.getValue($('#List_Search_StartTime'));
        //     var endTime=xhExtra.getValue($('#List_Search_EndTime'));
        //     var sNodeName=xhExtra.getValue($('#select_node'));
        //     var type=xhExtra.getValue($('#select_status'));
        //     var tsort=xhExtra.getValue($('#select_sort'));
        //     var province=$('#select_province').combobox('getText');
        //     var city=$('#select_city').combobox('getText');
        //     window.open(modelUrl+'plan/exportPlan?key='+key+'&startTime='+startTime+'&endTime='+endTime+'&sNodeName='+sNodeName+'&type='+type+'&tsort='+tsort+'&province='+province+'&city='+city);
        // });
        $btn_menu=$('#bt_list_state').menubutton({
            iconCls: 'fa fa-bars',
            menu: '#mm'
        });
        $($btn_menu.menubutton('options').menu).menu({
            onClick: function (item) {
                //item 的相关属性参见API中的menu
                var state;
                if(item.text=='启动'){
                    state=1;
                }else if(item.text=='未启动'){
                    state=2;
                }else if(item.text=='暂停') {
                    state = 3;
                }else if(item.text == '一键完成'){
                    state = 4;

                }
                if(planList.treegrid('getSelections').length==0){
                    window.top.swal('错误','请选择一个计划','error');
                    return false;
                }
                var kid=planList.treegrid('getSelections')[0]['keyId'];
                var id=planList.treegrid('getSelections')[0]['realId'];
                var type=planList.treegrid('getSelections')[0]['type'];
                if(type==1){

                    if(state!=4){
                        $.ajax({
                            url:modelUrl+'plan/changeState',
                            data:{id:id,state:state},
                            type:'POST',
                            success:function (data) {
                                $('#bt_list_search').click();
                                setTimeout(function(){
                                    planList.treegrid('select',kid);
                                }, 500);

                                // var params=getParams(id);
                                // planList.treegrid('reload',params);
                                // planList.treegrid('expand',kid);

                            },
                            error:function (data) {
                                console.log(data);
                            }
                        });
                    }else {
                        // $.ajax({
                        //     url:modelUrl+'plan/changeState',
                        //     data:{id:id,state:state},
                        //     type:'POST',
                        //     dataType:'json',
                        //     success:function (data) {
                        //         $('#bt_list_search').click();
                        //         setTimeout(function(){
                        //             planList.treegrid('select',kid);
                        //         }, 500);
                        //
                        //
                        //     },
                        //     error:function (data) {
                        //         console.log(data);
                        //     }
                        // });
                        xhExtra.askChangeStatus('bpm/plan/finishPlan',{id:id},null,'确定要一键完成吗？',function (res) {
                            window.top.xhTop.showSuccess(res.msg);
                            planList.treegrid('reload');
                        })
                    }
                }else {
                    window.top.swal('错误','请选择计划','error');
                }
            }
        })


        $node_menu=$('#bt_node_state').menubutton({
            iconCls: 'fa fa-bars',
            menu: '#mm1',
        });
        $($node_menu.menubutton('options').menu).menu({
            onClick: function (item) {
                //item 的相关属性参见API中的menu
                var state;
                if(item.text=='已完成'){
                    state=1;
                }else if(item.text=='未完成'){
                    state=0;
                }
                if(planList.treegrid('getSelections').length==0){
                    window.top.swal('错误','请选择一个节点','error');
                    return false;
                }
                var kid=planList.treegrid('getSelections')[0]['keyId'];
                var iBPCId=planList.treegrid('getSelections')[0]['realId'];
                var type=planList.treegrid('getSelections')[0]['type'];
                var pid=planList.treegrid('getSelections')[0]['iBPPId'];

                if(type==2){
                    if(planList.treegrid('getSelections')[0]['name']=='缴费程序'){
                        window.top.xhTop.showModal({
                            title:'财务确认',
                            content: '<iframe src="'+modelUrl+'plan/financeForm?iBPCId='+iBPCId+'&iNodeState='+state+'"  style="width: 100%;;border-style: none;padding: 0px;height: 200px"></iframe>',
                            size:'md',
                            button:'确认',
                            backClose:false
                        });
                    }else {
                        $.ajax({
                            url:modelUrl+'plan/changeNodeState',
                            data:{iBPCId:iBPCId,iNodeState:state},
                            type:'POST',
                            success:function (data) {
                                $('#bt_list_search').click();
                                setTimeout(function(){
                                    planList.treegrid('expand','P-'+pid);
                                    planList.treegrid('select',kid);
                                }, 500);

                            },
                            error:function (data) {
                                console.log(data);
                            }
                        });
                    }
                }else {
                    window.top.swal('错误','请选择节点','error');
                }
            }
        })




        $('#bt_list_confirm').click(function () {   //确认
            if(xhExtra.buttonDisabled($(this))){
                return false;
            }
            var id=planList.treegrid('getSelections')[0]['realId'];
            var type=planList.treegrid('getSelections')[0]['type'];
            if(type==1){
                myWindow.initPopUp({title: '确认锁定', text: '请确定该项目流程下所有信息填写完毕,计划完成时间将无法更改'},function () {
                    $.ajax({
                        url:modelUrl+'plan/lockContent',
                        data:{id:id},
                        type:'POST',
                        success:function (data) {
                            if(data == 'fail'){
                                window.top.xhTop.showMessage({title: '操作失败！', type: 'error'});
                                return false;
                            }else if(data == 'success'){
                                planList.treegrid('reload');
                            }else {
                                window.top.swal('操作失败', data, 'error')
                            }

                            //location.reload();
                        },
                        error:function (data) {
                            console.log(data);
                        }
                    });
                })
            }
        });

        $('#bt_list_unConfirm').click(function () {   //确认
            if(xhExtra.buttonDisabled($(this))){
                return false;
            }
            var id=planList.treegrid('getSelections')[0]['realId'];
            myWindow.initPopUp({title: '确认解锁', text: '解除已锁定信息'},function () {
                $.ajax({
                    url:modelUrl+'plan/lockContent/true',
                    data:{id:id},
                    type:'POST',
                    success:function (data) {
                        if(data == 'fail'){
                            window.top.xhTop.showMessage({title: '操作失败！', type: 'error'});
                            return false;
                        }else if(data == 'success'){
                            planList.treegrid('reload');
                        }else {
                            window.top.swal('操作失败', data, 'error')
                        }

                        //location.reload();
                    },
                    error:function (data) {
                        console.log(data);
                    }
                });
            })
        });



        $('#bt_list_del').click(function () {   //删除
            if(xhExtra.buttonDisabled($(this))){
                return false;
            }
            var id=planList.treegrid('getSelections')[0]['realId'];
            var type=planList.treegrid('getSelections')[0]['type'];
            if(type==1){
                myWindow.initPopUp({title: '确定要删除吗？', text: '该记录存在子记录'},function () {
                    $.ajax({
                        url:modelUrl+'plan/delPlan',
                        data:{id:id},
                        type:'POST',
                        success:function (data) {
                            window.top.xhTop.showSuccess(data.msg);
                            location.reload();
                        },
                        error:function (data) {
                            window.top.xhTop.showError(
                                data.responseJSON.error,
                                data.responseJSON.msg
                            );
                        }
                    });
                })
            }
        });
    }


    $('#bt_list_teachConfirm').click(function () {//教辅确认点击事件
        var id=planList.treegrid('getSelections')[0]['realId'];
        var type=planList.treegrid('getSelections')[0]['type'];
        var iCUId=planList.treegrid('getSelections')[0]['iCUId'];
        if(type==1){
            window.top.xhTop.showModal({
                title:'教辅确认',
                content: '<iframe src="'+modelUrl+'plan/teachConfirm?iBPPId='+id+'&iCUId='+iCUId+'"  style="width: 100%;;border-style: none;padding: 0px;height: 400px"  scrolling="yes"   ></iframe>',
                size:'lg',
                button:'提交',
                backClose: false,
            });
        }

    });




    $('#bt_list_search').click(function () {
        var province=$('#select_province').combobox('getText');
        var city=$('#select_city').combobox('getText');
        var params=getParams();
        planList.treegrid('load',params);
    });


    $("#select_province").combobox({
        onSelect: function(rec){
            var areaCode = rec.value;
            $('#select_city').combobox({
                url:modelUrl+'plan/getCity?areaCode='+areaCode,
                valueField:'areaCode',
                textField:'areaName'
            });
        }

    });

    //流程计划申领学生平板
    $('#bt_list_getStuTablet').click(function () {
        if (xhExtra.buttonDisabled($(this))) {
            return false;
        }
        var row = planList.treegrid('getSelected');
        if (row['bApplyTab'] == 0) {
            window.top.xhTop.showError('错误' , '该节点已关闭平板领用');
            return false;
        }
        window.top.xhTop.showModal({
            title:'学生机申请-'+row['name'],
            content: '<iframe src="'+baseUrl+'device/studentApply?iBPPId='+row['realId']+'"  style="width: 100%;;border-style: none;padding: 0px;height: 350px"  scrolling="yes"   ></iframe>',
            button:'提交',
            backClose:false
        });
    });
    
    //查看平板申领
    $('#bt_list_seeApplyTablet').click(function () {
        if (xhExtra.buttonDisabled($(this))) {
            return false;
        }
        var row = planList.treegrid('getSelected');
        window.top.xhTop.showModal({
            title:'设备申领-'+row['name'],
            content: '<iframe src="'+baseUrl+'bpm/plan/planTabletDetail?iBPPId='+row['realId']+'"  style="width: 100%;;border-style: none;padding: 0px;height: 600px"  scrolling="yes"   ></iframe>',
            size:'lg',
            backClose:false
        });

    });


    $('#alterCharger').menubutton({
        iconCls: 'fa fa-bars',
        menu: '#mm4',
    });


    //变更总负责人
    $('#bt_list_alterCharger').click(function () {
        var row = planList.treegrid('getSelected');
        window.top.xhTop.showModal({
            title:'变更总负责人-'+row['name'],
            content: '<iframe src="'+baseUrl+'bpm/plan/alterHeadCharger?iBPPId='+row['realId']+'"  style="width: 100%;;border-style: none;padding: 0px;height: 200px"  scrolling="yes"   ></iframe>',
            button:'提交',
            backClose:true,
            // onConfirm:false
        });
    });

    //查看负责人变更记录
    $('#bt_list_alterChargerLog').click(function () {
        var row = planList.treegrid('getSelected');
        var text = '<ul style="width: 90%;margin-left: 8px;">';
        xhExtra.ajaxRequest('bpm/plan/getAlterChargerLog', {id: row['realId']}, {
            check: true,
            async: false
        }, function (datas) {

            $.each(datas, function (index, data) {
                text += '<li style="list-style:none;padding-left: 20px;border-left: 1px solid #ddd;position: relative;' +
                    'padding-bottom: 20px;line-height: 24px;"><div>'
                    + data.tCreateDate
                    + '</div><div>'
                    + '</span> '
                    + data.sContent
                    + '</div><span style="width: 14px;height: 14px;background-color: #ddd;border-radius: 50%; '
                    + 'position: absolute;display: block; left: -7.5px;top: 0;"></span></li>';
            });
        });
        text += '</ul>';

        window.top.xhTop.showModal({
            title: '审批记录',
            content: '<div id="logs" style="width:100%;height: 350px;overflow-y: auto;overflow-x: hidden;">' + text + '</div>',
            backClose: false,
            size: 'md',
        });

    });



    // $("#cc2").combotree({
    //     onBeforeCheck: function (node) {
    //         //alert($("#combotree").combotree("tree").tree('isLeaf', node.target));
    //         if (!$("#cc2").combotree("tree").tree('isLeaf', node.target)) {
    //             return false;
    //         }
    //     }
    //
    // });






});

function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    return y+"-"+m+"-"+d;
}

function getParams(openId) {
    var key=xhExtra.getValue($('#list_search'));
    var startTime=xhExtra.getValue($('#List_Search_StartTime'));
    var endTime=xhExtra.getValue($('#List_Search_EndTime'));
    var sNodeName=xhExtra.getValue($('#select_node'));
    var type=xhExtra.getValue($('#select_status'));
    var tsort=xhExtra.getValue($('#select_sort'));
    var province=$('#select_province').combobox('getText');
    var city=$('#select_city').combobox('getText');
    var iState=$('#select_state').combobox('getValue');
    var all=xhExtra.getValue($('#select_all'));
    var receiveType = xhExtra.getValue($('#select_receiveType'));
    var params={key:key,startTime:startTime,endTime:endTime,sNodeName:sNodeName,type:type,tsort:tsort,province:province,city:city,openId:openId,all:all,iState:iState,receiveType:receiveType};
    return params;
}